package protocol.control;

import exceptions.ArgumentException;
import general.Bit;
import protocol.Frame;

/**
 * A receive request packet
 * @date 26.5.2011
 */
public class ReceiveRequestPacket implements Frame {

	private String filename;
	private long filesize;
	
	public String getFilename() {
		return this.filename;
	}

	public void setFilename(String filename) throws ArgumentException {
		if (filename.length() > 255) {
			throw new ArgumentException("Too long filename!");
		} else {
			this.filename = filename;
		}
	}

	public long getFilesize() {
		return this.filesize;
	}

	public void setFilesize(long filesize) {
		this.filesize = filesize;
	}

	/**
	 * Constructor
	 */
	public ReceiveRequestPacket() {		
	}
	
	/**
	 * Constructor
	 * @param bytes Supplied for the method parse()
	 */
	public ReceiveRequestPacket(byte[] bytes) {
		this.parse(bytes);
	}
	
	/**
	 * The specified packet format is:
	 * | 255 bytes | 64 bytes  |
	 * |-----------|-----------|
	 * | Filename  | File size |
	 * |-----------|-----------|
	 */
	public byte[] build() {
		byte[] data = new byte[319];
		/**
		 * Set the filename to the packet
		 */
		System.arraycopy(
			this.getFilename().getBytes(), 0, // source
			data, 0, // destination
			this.getFilename().getBytes().length); // copy length
		/**
		 * Set the filesize to the packet
		 */
		byte[] filesize = Bit.toByteArray(this.getFilesize());
		System.arraycopy(
			filesize, 0, // source
			data, 255, // destination
			8); // copy length
		return data;
	}

	/**
	 * The specified packet format is:
	 * | 255 bytes | 64 bytes  |
	 * |-----------|-----------|
	 * | Filename  | File size |
	 * |-----------|-----------|
	 */
	public void parse(byte[] bytes) {
		/**
		 * Save the filename
		 */
		byte[] filename = new byte[255];
		System.arraycopy(
			bytes, 0, // source
			filename, 0, // destination
			255); // copy length
		try {
			this.setFilename(new String(filename).trim());
		} catch (ArgumentException e) {
			System.err.println(e.toString());
		}
		/**
		 * Save the file size
		 */
		byte[] filesize = new byte[8];
		System.arraycopy(
			bytes, 254, // source
			filesize, 0,  // destination
			8); // copy length
		this.setFilesize(Bit.toLong(filesize));
	}
	
}